//
//  YMCheckSetOrAddUserInforVC.m
//  YMMedical
//
//  Created by y s on 2023/7/24.
//

#import "YMCheckSetOrAddUserInforVC.h"
#import "YMCheckUserInforTopItemCell.h"
#import "IQKeyboardManager.h"
#import "YMMedicalTools.h"
#import "YMMineService.h"
#import "YMCheckInformationModel.h"
#import "YMMineService.h"
#import "YMToolChooseStatusSheet.h"
#import "YMAddOrEditTestUserVC.h"
#import "YMHomeTipInforAlert.h"

#define xin_zeng_key KLanguage(@"newly_add_txt")
@interface YMCheckSetOrAddUserInforVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tvMain;
@property (nonatomic, strong) UIButton *btnSure;

@property (nonatomic, strong) YMToolChooseStatusSheet *sheetName;

@property (nonatomic, strong) NSArray *arrItem;
@property (nonatomic, strong) NSArray *arrUser;
/** 样品数据 */
@property (nonatomic, strong) NSMutableDictionary *dictSample;

@property (nonatomic, copy) NSString *nameStr;
@property (nonatomic, copy) NSString *heightStr;
@property (nonatomic, copy) NSString *yearStr;
@property (nonatomic, copy) NSString *weightStr;
@property (nonatomic, copy) NSString *sexStr;

/** 是否是新增 */
@property (nonatomic, assign) BOOL isNewAdd;
@property (nonatomic, assign) NSInteger indexName;

/** 如果是尿液判断是否是 含有24小时尿液选项 */
@property (nonatomic, assign) BOOL have24;
@property (nonatomic, assign) BOOL isSelect24;



@end

@implementation YMCheckSetOrAddUserInforVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self loadData];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    [self loadUserListData];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)setUI{
    [self showNavTitle:KLanguage(@"tester_and_info_txt")];
    [SNavUtil rightIcon:self icon:@"tools_nav_home_icon" onClick:^{
        [YMBridging goHomeTabWithAlert];
    }];
    [self.view addSubview:self.tvMain];
    [self.view addSubview:self.btnSure];
    [self.tvMain mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
    }];
    [self.btnSure mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.bottom.mas_equalTo([SFitUtil fit:-15]-IPHONE_X_BOTTOM_HEIGHT);
        make.size.mas_equalTo([SFitUtil fitSize:345 height:54]);
        make.top.equalTo(self.tvMain.mas_bottom).offset([SFitUtil fit:15]);
    }];
}

- (void)loadData{
    WEAK_SELF;
    self.have24 = NO;
    [YMCheckService requestCheckUserInforListBottomItemDataWithIdStr:self.checkModel.minorTermId success:^(NSString * _Nonnull nameStr, NSArray *arrItem) {
        weakSelf.arrItem = arrItem;
        for (int i = 0; i < arrItem.count; i++) {
            NSString *keyStr = [NSString stringWithFormat:@"key_%d",i];
            NSDictionary *dict = [SDataUtil dictOf:arrItem[i]];
            NSString *fieldName = [SDataUtil stringOf:dict[@"fieldName"]];
            NSArray *arrOptions = [SDataUtil arrayOf:dict[@"options"]];
            if ([fieldName containsString:@"sampleVolume"]){
                weakSelf.have24 = YES;
            }
            for (NSString *itemStr in arrOptions) {
                if ([itemStr containsString:@"24"]){
                    weakSelf.isSelect24 = YES;
                    [weakSelf.dictSample setValue:itemStr forKey:keyStr];
                }
            }
        }
        [weakSelf.tvMain reloadData];
    } failure:^(NSString * _Nonnull message) {
        [SHUD showInfo:message];
    }];
}

- (void)loadUserListData{
    WEAK_SELF;
    [YMMineService requestMineTesteeListDataWithPage:1 needpage:0 success:^(NSArray * _Nonnull arrData) {
        weakSelf.arrUser = arrData;
        if (arrData.count > 0){
            weakSelf.isNewAdd = NO;
            NSMutableArray *arrTemp = [[NSMutableArray alloc] init];
            for (NSDictionary *item in arrData) {
                NSString *name = [SDataUtil stringOf:item[@"8pa55qzbspju5tzn"] valid:@""];
                NSString *userId = [SDataUtil stringOf:item[@"id"] valid:@""];
                if (userId != nil && userId.length > 0 &&
                    [[YMMyModel shared].homeUserId isEqualToString:userId]){
                    weakSelf.indexName = [arrData indexOfObject:item];
                }
                [arrTemp addObject:name];
            }
            [weakSelf changeUserInforData];
            [YMMyModel shared].homeUserId = @"";
            [arrTemp addObject:xin_zeng_key];
            weakSelf.sheetName.arrData = [arrTemp copy];
        }else{
            weakSelf.isNewAdd = YES;
        }
        [weakSelf.tvMain reloadData];
    } failure:^(NSString * _Nonnull message) {
        [SHUD hide:weakSelf.view];
        [SHUD showInfo:message];
    }];
}


#pragma mark -- Event action
- (void)sureClickAction:(id)sender{
    if (self.nameStr == nil || self.nameStr.length < 1){
        if (_isNewAdd){
            [SHUD showInfo:KLanguage(@"input_name_txt")];
        }else{
            [SHUD showInfo:KLanguage(@"choose_testee_txt")];
        }
        return;
    }
    if (self.sexStr == nil || self.sexStr.length < 1){
        [SHUD showInfo:KLanguage(@"choose_gender")];
        return;
    }
    if (self.yearStr == nil || self.yearStr.length < 1){
        [SHUD showInfo:KLanguage(@"choose_birth_txt")];
        return;
    }
    if (self.heightStr == nil || self.heightStr.length < 1){
        [SHUD showInfo:KLanguage(@"input_tall_txt")];
        return;
    }
    if (self.weightStr == nil || self.weightStr.length < 1){
        [SHUD showInfo:KLanguage(@"input_weight_fx_txt")];
        return;
    }
    BOOL allTrue = YES;
    for (int i = 0; i < self.arrItem.count; i++) {
        NSDictionary *dictItem = [SDataUtil dictOf:self.arrItem[i]];
        NSString *keyStr = [NSString stringWithFormat:@"key_%d",i];
        NSString *valueStr = [SDataUtil stringOf:self.dictSample[keyStr] valid:@""];
        NSString *fieldName = [SDataUtil stringOf:dictItem[@"fieldName"]];
        if (valueStr == nil || valueStr.length < 1){
            if (_have24 && [fieldName containsString:@"sampleVolume"]){
                if (_isSelect24){
                    [SHUD showInfo:[SDataUtil stringOf:dictItem[@"prompt"] valid:@""]];
                    allTrue = NO;
                    return;
                }
            }else{
                [SHUD showInfo:[SDataUtil stringOf:dictItem[@"prompt"] valid:@""]];
                allTrue = NO;
                return;
            }
        }
    }
    if (allTrue == NO){
        return;
    }
    WEAK_SELF;
    [SHUD showWait:self.view];
    if (_isNewAdd){
        [YMMineService requestMineTesteeManagerSearchDataWithName:self.nameStr success:^(NSArray * _Nonnull arrData) {
            [SHUD hide:weakSelf.view];
            if (arrData.count > 0){
                YMHomeTipInforAlert *alert = [[YMHomeTipInforAlert alloc] init];
                alert.iconName = @"alert_tips_infor_icon";
                alert.strContent = KLanguage(@"same_tester_name_txt");
                alert.sureBlock = ^{
                    [weakSelf requestAddNew];
                };
                [alert show];
            }else{
                [weakSelf requestAddNew];
            }
        } failure:^(NSString * _Nonnull message) {
            [SHUD hide:weakSelf.view];
            [SHUD showInfo:message];
        }];

    }else{
        NSDictionary *dictUser = [SDataUtil dictOf:self.arrUser[_indexName]];
        [YMMineService requestMineEditTesteeInformationWithName:self.nameStr height:self.heightStr sex:[YMMedicalTools sexName:self.sexStr] year:self.yearStr weight:self.weightStr rowid:[SDataUtil stringOf:dictUser[@"id"] valid:@""] success:^(NSString * _Nonnull idStr) {
            [SHUD hide:weakSelf.view];
            [weakSelf dealWithResultData:idStr];
        } failure:^(NSString * _Nonnull message) {
            [SHUD hide:weakSelf.view];
            [SHUD showInfo:message];
        }];
    }

    
}
- (void)requestAddNew{
    WEAK_SELF;
    [YMMineService requestMineAddNewTesteeWithName:self.nameStr height:self.heightStr sex:[YMMedicalTools sexName:self.sexStr] year:self.yearStr weight:self.weightStr success:^(NSString * _Nonnull idStr) {
        [SHUD hide:weakSelf.view];
        [weakSelf dealWithResultData:idStr];
    } failure:^(NSString * _Nonnull message) {
        [SHUD hide:weakSelf.view];
        [SHUD showInfo:message];
    }];
}
- (void)dealWithResultData:(NSString *)idStr{
    NSString *personId = @"";
    if (self.arrUser.count > self.indexName){
        NSDictionary *dictName = [SDataUtil dictOf:self.arrUser[self.indexName]];
        personId = [SDataUtil stringOf:dictName[@"id"] valid:@""];
    }
    self.checkModel.detectionUserId = [SDataUtil stringOf:idStr valid:personId];
    self.checkModel.detectionUserName = [SDataUtil stringOf:self.nameStr valid:@""];
    self.checkModel.gender = [SDataUtil stringOf:_sexStr valid:@""];
    self.checkModel.birthday = [SDataUtil stringOf:_yearStr valid:@""];
    self.checkModel.age = [YMMedicalTools calculateYearToNow:_yearStr];
    self.checkModel.height = [SDataUtil stringOf:_heightStr valid:@""];
    self.checkModel.weight = [SDataUtil stringOf:_weightStr valid:@""];
    
    NSMutableDictionary *dictPara = [[NSMutableDictionary alloc] init];
    for (int i = 0; i < self.arrItem.count; i++) {
        NSDictionary *dictItem = [SDataUtil dictOf:self.arrItem[i]];
        NSString *oldKey = [NSString stringWithFormat:@"key_%d",i];
        NSString *valueStr = [SDataUtil stringOf:self.dictSample[oldKey] valid:@""];
        
        NSString *keyStr = [SDataUtil stringOf:dictItem[@"fieldName"] valid:@""];
        if (_have24 && [keyStr isEqualToString:@"sampleVolume"]){
            if (_isSelect24){
                [dictPara setValue:valueStr forKey:keyStr];
            }else{
                [dictPara setValue:@"" forKey:keyStr];
            }
        }else{
            [dictPara setValue:valueStr forKey:keyStr];
        }
    }
    self.checkModel.dictSample = [dictPara copy];
    if (self.finishBlock){
        self.finishBlock(self.checkModel);
    }
    
}
- (void)changeUserInforData{
    
    if (self.indexName > self.arrUser.count-1){
        self.indexName = 0;
    }
    if (self.arrUser.count > self.indexName){
        NSDictionary *dictName = [SDataUtil dictOf:self.arrUser[self.indexName]];
        self.nameStr = [SDataUtil stringOf:dictName[@"8pa55qzbspju5tzn"] valid:@""];
        self.heightStr = [SDataUtil stringOf:dictName[@"cu8thtdjxhfbxpjx"] valid:@""];
        self.weightStr = [SDataUtil stringOf:dictName[@"yzqfbls6zzqh9tyl"] valid:@""];
        self.sexStr = [SDataUtil stringOf:dictName[@"kpurkwtmvsd9lqui"] valid:@""];
        
        NSString *dateStr = [SDataUtil stringOf:dictName[@"orldw605kccdju8z"] valid:@""];
        self.yearStr = dateStr;
    }
    [self.tvMain reloadData];
}

#pragma mark -- UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (_have24 && _isSelect24 == NO){
        return 6+self.arrItem.count-1;
    }else{
        return 6+self.arrItem.count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    __block NSInteger section = indexPath.section;
    if (section == 0){
        YMCheckUserInforTopItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YMCheckUserInforTopItemCell" forIndexPath:indexPath];
        cell.itemTitle = self.checkModel.minorTermName;
        return cell;
    }else{
        YMCheckUserInforListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if (cell == nil){
            cell = [[YMCheckUserInforListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"YMCheckUserInforListCell"];
        }
        cell.maxLenth = 0;
        cell.maxNum = 0;
        WEAK_SELF;
        if (section < 6){
            if (section == 1){
                cell.titleStr = KLanguage(@"name_txt");
                cell.maxLenth = 12;
                if (self.isNewAdd == NO){
                    cell.isChoose = YES;
                    cell.placeholder = KLanguage(@"choose_testee_txt");
                }else{
                    cell.isChoose = NO;
                    cell.placeholder = KLanguage(@"input_name_txt");
                }
                cell.keyboardType = UIKeyboardTypeDefault;
                cell.inputText = self.nameStr;
            }else if (section == 2){
                cell.titleStr = KLanguage(@"gender_txt");
                cell.isChoose = YES;
                cell.placeholder = KLanguage(@"choose_gender");
                cell.inputText = [YMMedicalTools showGender:self.sexStr];
            }else if (section == 3){
                cell.titleStr = KLanguage(@"birthdat_txt");
                cell.isChoose = YES;
                cell.placeholder = KLanguage(@"choose_txt");
                cell.inputText = self.yearStr;
            }else if (section == 4){
                cell.titleStr = KLanguage(@"tall_txt");
                cell.isChoose = NO;
                cell.placeholder = KLanguage(@"input_tall_txt");
                cell.keyboardType = UIKeyboardTypeDecimalPad;
                cell.inputText = self.heightStr;
                cell.maxNum = 250;
            }else if (section == 5){
                cell.titleStr = KLanguage(@"weight_txt");
                cell.isChoose = NO;
                cell.placeholder = KLanguage(@"input_weight_fx_txt");
                cell.keyboardType = UIKeyboardTypeDecimalPad;
                cell.inputText = self.weightStr;
                cell.maxNum = 400;
            }
           
            cell.textChangeBlock = ^(NSString * _Nonnull text) {
                if (section == 1){
                    //姓名
                    weakSelf.nameStr = text;
                }else if (section == 4){
                    //身高
                    weakSelf.heightStr = text;
                }else if (section == 5){
                    //体重
                    weakSelf.weightStr = text;
                }
            };
            cell.chooseBlock = ^{
                [weakSelf.view endEditing:YES];
                if (section == 1){
                    //姓名
                    [weakSelf showChooseUser:indexPath];
                }else if (section == 2){
                   //性别
                    [weakSelf showChooseSexSheet:indexPath];
                }else if (section == 3){
                   //出生日期
                    [weakSelf showChooseDateSheet:indexPath];
                }
            };
            
        }else{
            __block NSInteger index = section - 6;
            if (index < self.arrItem.count)
            {
                __block NSString *keyStr = [NSString stringWithFormat:@"key_%ld",index];
                __block NSDictionary *dictItem = [SDataUtil dictOf:self.arrItem[index]];
                cell.titleStr = [SDataUtil stringOf:dictItem[@"fieldTxt"]];
                __block NSString *fieldType = [SDataUtil stringOf:dictItem[@"fieldType"]];
                if ([fieldType isEqualToString:@"select"] ||
                    [fieldType isEqualToString:@"date"]){
                    cell.isChoose = YES;
                }else{
                    cell.isChoose = NO;
                }
                if ([fieldType isEqualToString:@"number"]){
                    cell.keyboardType = UIKeyboardTypeDecimalPad;
                }else{
                    cell.keyboardType = UIKeyboardTypeDefault;
                }
                cell.placeholder = [SDataUtil stringOf:dictItem[@"prompt"]];
                cell.inputText = [SDataUtil stringOf:self.dictSample[keyStr] valid:@""];
                cell.chooseBlock = ^{
                    [weakSelf.view endEditing:YES];
                    if ([fieldType isEqualToString:@"date"]){
                        [weakSelf showChooseDateSheet:indexPath keyStr:keyStr];
                    }else{
                        [weakSelf showChooseSelectTypeSheet:indexPath dict:dictItem keyStr:keyStr];
                    }
                };
                cell.textChangeBlock = ^(NSString * _Nonnull text) {
                    [weakSelf.dictSample setValue:[SDataUtil stringOf:text valid:@""] forKey:keyStr];
                };
            }
        }
        return cell;
    }
}
- (void)showChooseDateSheet:(NSIndexPath *)indexPath{
    WEAK_SELF;
    [YMMedicalTools chooseBirthDay:^(NSString * _Nonnull year) {
        YMCheckUserInforListCell *cell = [weakSelf.tvMain cellForRowAtIndexPath:indexPath];
        cell.inputText = year;
        weakSelf.yearStr = year;
    }];
}
- (void)showChooseSexSheet:(NSIndexPath *)indexPath{
    WEAK_SELF;
    [YMMedicalTools chooseSexSheet:^(NSString * _Nonnull sex, NSInteger index) {
        YMCheckUserInforListCell *cell = [weakSelf.tvMain cellForRowAtIndexPath:indexPath];
        cell.inputText = sex;
        weakSelf.sexStr = sex;
    }];
}
- (void)showChooseUser:(NSIndexPath *)indexPath{
    WEAK_SELF;
    self.sheetName.textSureBlock = ^(NSString * _Nonnull text, NSInteger index) {
        if ([text isEqualToString:xin_zeng_key]){
            YMAddOrEditTestUserVC *vc = [[YMAddOrEditTestUserVC alloc] init];
            vc.isAddNew = YES;
            [SJumpUtil pushVC:vc animated:YES];
        }else{
            weakSelf.indexName = index;
            [weakSelf changeUserInforData];
        }
    };
    [self.sheetName show];
}
- (void)showChooseSelectTypeSheet:(NSIndexPath *)indexPath
                             dict:(NSDictionary *)dictItem
                           keyStr:(NSString *)keyStr{
    WEAK_SELF;
    NSArray *arrTemp = [SDataUtil arrayOf:dictItem[@"options"]];
    if (arrTemp != nil && arrTemp.count > 0){
        YMToolChooseStatusSheet *vSheet = [[YMToolChooseStatusSheet alloc] init];
        vSheet.arrData = arrTemp;
        vSheet.textSureBlock = ^(NSString * _Nonnull text, NSInteger index) {
            YMCheckUserInforListCell *cell = [weakSelf.tvMain cellForRowAtIndexPath:indexPath];
            cell.inputText = text;
            if ([text containsString:@"24"]){
                weakSelf.isSelect24 = YES;
            }else{
                weakSelf.isSelect24 = NO;
            }
            [weakSelf.dictSample setValue:[SDataUtil stringOf:text valid:@""] forKey:keyStr];
            [weakSelf.tvMain reloadData];
        };
        [vSheet show];
    }
}
- (void)showChooseDateSheet:(NSIndexPath *)indexPath
                     keyStr:(NSString *)keyStr{
    WEAK_SELF;
    [YMMedicalTools chooseBirthDay:^(NSString * _Nonnull year) {
        YMCheckUserInforListCell *cell = [weakSelf.tvMain cellForRowAtIndexPath:indexPath];
        cell.inputText = year;
        [weakSelf.dictSample setValue:[SDataUtil stringOf:year valid:@""] forKey:keyStr];
        [weakSelf.tvMain reloadData];
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return [[UIView alloc] init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger section = indexPath.section;
    if (section == 0){
        return [YMCheckUserInforTopItemCell getCellHeight];
    }else {
        return [SFitUtil fit:50];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return [SFitUtil fit:15];
}

#pragma mark -- setter and getter
- (UITableView *)tvMain{
    if (!_tvMain) {
        _tvMain = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tvMain.backgroundColor = [UIColor clearColor];
        _tvMain.delegate   = self;
        _tvMain.dataSource = self;
        _tvMain.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tvMain.showsVerticalScrollIndicator   = NO;
        _tvMain.showsHorizontalScrollIndicator = NO;
        _tvMain.estimatedRowHeight = 0;
        _tvMain.estimatedSectionHeaderHeight = 0;
        _tvMain.estimatedSectionFooterHeight = 0;
        [_tvMain registerClass:[YMCheckUserInforTopItemCell class] forCellReuseIdentifier:@"YMCheckUserInforTopItemCell"];
        
        _tvMain.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    return _tvMain;
}
- (UIButton *)btnSure{
    if (_btnSure == nil){
        _btnSure = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnSure setTitle:KLanguage(@"sure_txt_key") forState:UIControlStateNormal];
        [_btnSure setTitleColor:STheme.D9 forState:UIControlStateNormal];
        _btnSure.titleLabel.font = [SFitUtil fitBoldFont:16];
        [_btnSure addTarget:self action:@selector(sureClickAction:) forControlEvents:UIControlEventTouchUpInside];
        _btnSure.backgroundColor = STheme.D12;
        _btnSure.layer.cornerRadius = [SFitUtil fit:10];
        _btnSure.clipsToBounds = YES;
    }
    return _btnSure;
}
- (NSMutableDictionary *)dictSample{
    if (_dictSample == nil){
        _dictSample = [[NSMutableDictionary alloc] init];
    }
    return _dictSample;
}
- (YMToolChooseStatusSheet *)sheetName{
    if (_sheetName == nil){
        _sheetName = [[YMToolChooseStatusSheet alloc] init];
    }
    return _sheetName;
}

@end
